package com.zhang.es;

import com.alibaba.fastjson.JSON;
import com.zhang.entity.User;
import com.zhang.util.GetEsConnClient;
import java.io.IOException;
import java.util.List;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;

/**
 * 描述:es新增数据接口类
 *
 * @author Zhao
 * @create 2022-04-15 0:50
 */
public class EsInsert {

    private static final RestHighLevelClient CLIENT = GetEsConnClient.getClient();

    public static void insertData(List<User> users){

        try {
            //创建索引
            EsIndex.createIndex("user");

            //插入数据
            BulkRequest request = new BulkRequest();
            for (int i = 0; i < users.size(); i++) {
                User user = users.get(i);
                request.add(new IndexRequest().index("user").id(String.valueOf(i)).source(
                    JSON.toJSONString(user), XContentType.JSON));
            }

            BulkResponse responses = CLIENT.bulk(request, RequestOptions.DEFAULT);
            System.out.println(responses.getTook());
            CLIENT.close();
        } catch (Exception e) {
            try {
                CLIENT.close();
            } catch (IOException ex) {
                throw new RuntimeException(ex);
            }
            throw new RuntimeException(e);
        }
    }
    public static void close(){
        try {
            CLIENT.close();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}
